package leetcode.editor.cn.q0xx

class Q27 {
    fun removeElement(nums: IntArray, `val`: Int): Int {
        if (nums.isEmpty()) return 0

        var size = nums.size
        var j = nums.lastIndex
        for (i in nums.indices) {
            if (nums[i] == `val`) {
                size--
                while (nums[j] == `val` && j > i) {
                    j--
                    size--
                }
                if (j > i) {
                    nums[i] = nums[j]
                    j--
                }
                if (j <= i) {
                    break
                }
            }
        }

        return size
    }
}